package com.siyoumi.app.sys.app;

import com.siyoumi.app.sys.service.WxTokenService;
import com.siyoumi.app.sys.service.web_oauth.WebOauth;
import com.siyoumi.app.sys.service.wx_center.CenterHandler;
import com.siyoumi.app.sys.vo.WxJsSdkVo;
import com.siyoumi.app.sys.vo.WebOauthVo;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.ApiController;
import com.siyoumi.entity.SysAccsuperConfig;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.service.SysAccsuperConfigService;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//公众号授权
//http://dev.x.siyoumi.com/web/oauth_re?x=x&app_id=prize
//http://dev.x.siyoumi.com/web/oauth_re?x=x&app_id=prize&code=test&test_uid=oYKGq5cSr5QBkE9eNpnk_JCYl0qY
@Slf4j
@RestController
@RequestMapping("/web")
public class ApiWebOauth
        extends ApiController {
    //授权
    @SneakyThrows
    @RequestMapping("oauth_re")
    public void oauthRe(@Validated WebOauthVo data, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true, true);

        String url = WebOauth.getIns(data.getX()).reHandle(data);
        getResponse().sendRedirect(url);
    }

    //授权回调
    @SneakyThrows
    @RequestMapping("oauth_callback")
    public void oauthCallback(@Validated WebOauthVo data, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true, true);

        String url = WebOauth.getIns(data.getX()).callbackHandle(data);
        getResponse().sendRedirect(url);
    }

    //公众号或者小程序webview调用接口
    @SneakyThrows
    @GetMapping("js_sdk")
    public WxJsSdkVo jsSdk(@Validated WxJsSdkVo vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true, true);

        SysAccsuperConfig entityConfig = SysAccsuperConfigService.getBean().getXConfig(vo.getX(), true);
        if (entityConfig == null) {
            XValidator.err(20114, "x error");
        }

        String jsTicket = WxTokenService.getBean(entityConfig).getJsTicket();
        vo.setAppId(entityConfig.getAconfig_app_id());
        vo.setJsapi_ticket(jsTicket);

        //签名
        String[] ss = new String[]{
                "noncestr=" + vo.getNonceStr(),
                "jsapi_ticket=" + vo.getJsapi_ticket(),
                "timestamp=" + vo.getTimestamp(),
                "url=" + vo.getUrl(),
        };
        String sign = CenterHandler.getSign(ss);
        vo.setSignature(sign);


        return vo;
    }
}
